﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cos.Core.Model.Template;
using Cos.Core.NHibernate;
using Cos.Core.NHibernate.Util;
using Cos.Module.Template.Data;
using Microsoft.Practices.Unity;
using NHibernate;
using NHibernate.Criterion;

namespace Cos.Module.Template.NHibernate
{
    public class TemplateRepository : RepositoryBase, ITemplateRepository
    {
        [InjectionConstructor]
        public TemplateRepository(ISessionFactory sessionFactory)
            : base(sessionFactory)
        {
        }

        public Cos.Core.Model.Template.Template GetTemplate(int templateId)
        {
            var template = this.CurrentSession.Get<TemplateDataModel>(templateId);
                
            if (template == null)
            {
                return null;
            }

            return template.ToTemplate();
        }

        public IEnumerable<Core.Model.Template.Template> GetTemplates()
        {
            return CurrentSession.CreateCriteria<TemplateDataModel>()
                                 .List<TemplateDataModel>()
                                 .Select(x => x.ToTemplate());
        }

        public Cos.Core.Model.Template.Template SaveTemplate(Cos.Core.Model.Template.Template template)
        {
            var templateDataModel = this.CurrentSession.Get<TemplateDataModel>(template.TemplateId).ToTemplateDataModel(template);

            this.CurrentSession.SaveOrUpdate(templateDataModel);

            this.CurrentSession.Flush();

            return templateDataModel.ToTemplate();
        }
    }
}
